/*
 * @lc app=leetcode.cn id=92 lang=golang
 *
 * [92] 反转链表 II
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func reverseBetween(head *ListNode, m int, n int) *ListNode {
	var prem, nodem, aftern *ListNode
	i := 1
	current := head
	for i <= n+1 {
		if i+1 == m {
			prem = current
		}

		if i == m {
			nodem = current
		}

		if i == n+1 {
			aftern = current
		}

		current = current.Next
		i++
	}

	prem.Next = reverse(nodem, aftern)
	return prem
}

func reverse(head, last *ListNode) *ListNode {
	prev := last
	current := head
	for current != last {
		tmp := current.Next
		current.Next = prev
		prev = current
		current.Next = tmp
	}
	return prev
}

// @lc code=end

